<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()

const search = computed({
  get() {
    return route.query.search ?? ''
  },
  set(search) {
    router.replace({ query: { search } })
  }
})

const goNotFound = () => {
	router.push({
		name: 'NotFound',
		// 保留当前路径并删除第一个字符，以避免目标 URL 以 `//` 开头。
		params: { pathMatch: route.path.substring(1).split('/') },
		// 保留现有的查询和 hash 值，如果有的话
		query: route.query,
		hash: route.hash,
	})
}
</script>

<template>
  <h2>UserView</h2>
	<pre>
		{{$route}}-{{$route.path}}-{{$route.path.substring(1)}}-{{$route.path.substring(1).split('/')}}
	</pre>
  <label>
    Search: <input v-model.trim="search" maxlength="20">
  </label>
  <div>
    <!-- 当前路由 可以通过 $route 在模板中访问 -->
    User {{ $route.params.id }}
  </div>
	<button @click.stop="goNotFound">Go to NotFound【路由的匹配方法】</button>
</template>